//
//  YXNetWork.swift
//  SinaWeiBo
//
//  Created by Vergil on 2017/5/22.
//  Copyright © 2017年 Vergil. All rights reserved.
//

import UIKit
import AFNetworking

enum MethodType {
    case Get
    case Post
}

class YXNetWork: AFHTTPSessionManager {
    
    lazy var userModel = YXNetWorkModel()
    
    //计算型属性,用户是否登录
    var userLogin: Bool {
        return userModel.access_token != nil
    }
    
    //单例
    static let Manager = { () -> YXNetWork in 
        
        let instance = YXNetWork()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
        
    }()
    
    func netWorkRequest(method: MethodType = .Get, URLString: String, parameters: [String : Any]?, completion: @escaping (_ json: Any?, _ isSussess: Bool)->()) {
        
        //判断token是否有值
        guard let accessToken = userModel.access_token else {
            //提示用户还没有登录
            print("还没有登录")
            
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginNotification), object: nil)
            
            completion(nil, false)
            
            return
        }
        
        var parameters = parameters
        
        if parameters == nil {
            //如果没参数就初始化一个空的
            parameters = [String : Any]()
        }
        parameters!["access_token"] = accessToken
        
        baseRequest(method: method, URLString: URLString, parameters: parameters!, completion: completion)
    }
    
    func baseRequest(method: MethodType = .Get, URLString: String, parameters: [String : Any], completion: @escaping (_ json: Any?, _ isSussess: Bool)->()) {
        
        let success = { (task: URLSessionDataTask, json: Any?) -> () in
            completion(json, true)
        }
        
        let failure = { (task: URLSessionDataTask?, error: Error) -> () in
            if (task?.response as! HTTPURLResponse).statusCode == 403 {
                print("Token已过期")
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginNotification), object: "bad token")
            }
            print("-------\(error)")
            completion(nil, false)
        }
        
        if method == .Get {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }
    
}
